const { User } = require('../db')
const { encryptPassword } = require('../util/security')

async function verifyOldPassword (ctx, next) {
  const user = await User.findById(ctx.user.id)
  if (user && user.password === encryptPassword(ctx.request.body.oldPassword)) {
    ctx.tl = {
      ...user._doc
    }
    await next()
  } else {
    ctx.throw('用户不存在或旧密码错误')
  }
}

// 判断邮箱是否已完成验证
async function emailVerified (ctx, next) {
  const user = await User.findById(ctx.user.id)
  if (user.state === -1) {
    ctx.throw('请先验证邮箱')
  } else {
    await next()
  }
}

module.exports = {
  verifyOldPassword,
  emailVerified
}
